package com.ewhale.feitengguest.receiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.ewhale.feitengguest.ui.user.MainActivity;
import com.ewhale.feitengguest.ui.auth.SplashActivity;
import com.ewhale.feitengguest.ui.user.mine.InviteActivity;
import com.ewhale.feitengguest.ui.user.mine.MyWalletActivity;
import com.simga.library.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            LogUtil.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                LogUtil.d(TAG, "[MyReceiver] 用户点击打开了通知");
                Intent newIntent = new Intent();
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                if (!isUIProcess(context)) {
                    newIntent.setClass(context, SplashActivity.class);
                    context.startActivity(newIntent);
                    return;
                }
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    String myKey = json.optString("type");
                    switch (myKey) {
                        case "systemMessage"://系统消息
                            if (isAppForeground(context)) {
                                if (isActivityTop(context, "MainActivity")) {
                                    context.sendBroadcast(new Intent("JUMP_MESSAGE"));
                                } else {
                                    newIntent.setClass(context, MainActivity.class);
                                    context.startActivity(newIntent);
                                }
                            } else {
                                newIntent.setClass(context, MainActivity.class);
                                context.startActivity(newIntent);
                            }
                            break;
                        case "withdrawalSuccess"://提现消息
                        case "walletBalanceUpdate"://资金调整
                            if (!isAppForeground(context)) {
                                newIntent.setClass(context, MainActivity.class);
                                context.startActivity(newIntent);
                                return;
                            }
                            if (!isActivityTop(context, "MyWalletActivity")) {
                                newIntent.setClass(context, MyWalletActivity.class);
                                context.startActivity(newIntent);
                            }
                            break;
                        case "commitMission"://提交任务消息
                            break;
                        case "missionPriceArrive"://佣金到账
                            if (!isAppForeground(context)) {
                                newIntent.setClass(context, MainActivity.class);
                                context.startActivity(newIntent);
                                return;
                            }
                            if (!isActivityTop(context, "InviteActivity")) {
                                newIntent.setClass(context, InviteActivity.class);
                                context.startActivity(newIntent);
                            }
                            break;
                        case "missionAuthMessage":
//                            if (!isAppForeground(context)) {
//                                newIntent.setClass(context, MainActivity.class);
//                                context.startActivity(newIntent);
//                                return;
//                            }
//                            if (!isActivityTop(context, "MyTaskDetailActivity")) {
//                                newIntent.setClass(context, MyTaskDetailActivity.class);
//                                context.startActivity(newIntent);
//                            }
                            break;
                        default:
                            if (!isAppForeground(context)) {
                                newIntent.setClass(context, MainActivity.class);
                                context.startActivity(newIntent);
                                return;
                            }
                            break;
                    }
                } catch (JSONException e) {
                    LogUtil.e(TAG, "Get message extra JSON error!");
                }
            }
        } catch (Exception e) {
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    LogUtil.i(TAG, "This message has no Extra data");
                    continue;
                }
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();
                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    LogUtil.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }


    //true:当前进程是主进程 false:当前进程不是主进程
    public boolean isUIProcess(Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    //app是否在前台
    private boolean isAppForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
            return true;
        }
        return false;
    }

    /**
     * 判断某个页面是不是在第一个页面
     *
     * @param context
     * @param className
     * @return
     */
    private boolean isActivityTop(Context context, String className) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String activityName = am.getRunningTasks(1).get(0).topActivity.getClassName();
        try {
            Class classObject = Class.forName(activityName);
            if (classObject.getSimpleName().equals(className)) {
                return true;
            }
            return false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
}
